package xyz.riceball.develop.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xyz.riceball.develop.entity.dto.SqlDefinitionDTO;
import xyz.riceball.develop.entity.po.RoutePO;
import xyz.riceball.develop.entity.po.SqlDefinitionPO;
import xyz.riceball.develop.mapper.DevelopRouteMapper;
import xyz.riceball.develop.mapper.SqlDefinitionMapper;
import xyz.riceball.develop.service.SqlDefinitionService;
import xyz.riceball.framework.core.bean.ApiR;
import xyz.riceball.framework.core.context.UserContext;
import xyz.riceball.framework.core.enums.ENBool;
import xyz.riceball.framework.core.util.BeanUtils;
import xyz.riceball.framework.core.util.TransactionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * SQL定义 Service实现层
 *
 * @author xiaovcloud
 * @since 2022-07-02 10:58:37
 */
@Slf4j
@Service("sqlDefinitionService")
public class SqlDefinitionServiceImpl extends ServiceImpl<SqlDefinitionMapper, SqlDefinitionPO> implements SqlDefinitionService {

    @Resource
    private DevelopRouteMapper developRouteMapper;

    @Override
    public Page<SqlDefinitionPO> selectPage(Page<SqlDefinitionPO> page, SqlDefinitionPO sqlDefinitionPO) {
        return getBaseMapper().selectPage(page, null);
    }

    @Override
    public ApiR<SqlDefinitionDTO> add(SqlDefinitionDTO sqlDefinitionDTO) {
        if (ENBool.TRUE.intValue() != sqlDefinitionDTO.getLinkRoute()) {
            //不存在子功能
            RoutePO routePO = new RoutePO();
            BeanUtils.copyWithoutNull(routePO, sqlDefinitionDTO);
            routePO.setOnline(ENBool.TRUE.intValue());

            TransactionUtils.doInTransactionWithRequired(() -> {
                developRouteMapper.insert(routePO);
                sqlDefinitionDTO.setRouteId(routePO.getId());
                getBaseMapper().insert(sqlDefinitionDTO);
                return Void.class;
            });
        } else {
            //存在子功能
            BeanUtils.buildAutoField(sqlDefinitionDTO, true, UserContext.getUserId());
            getBaseMapper().insert(sqlDefinitionDTO);
        }
        return ApiR.okMsgAndData("新增SQL定义成功", sqlDefinitionDTO);
    }

    @Override
    public boolean edit(SqlDefinitionPO sqlDefinitionPO) {

        return false;
    }

    @Override
    public ApiR delete(List<String> ids) {
        return null;
    }
}